<?php
/**
 * Created by PhpStorm.
 * User: Sergey
 * Date: 14.03.14
 * Time: 21:31
 */

include_once BASE_DQ_PLUGIN_PATH . "classes/Config.php";
include_once BASE_DQ_PLUGIN_PATH . "classes/ConnectionFactory.php";
include_once BASE_DQ_PLUGIN_PATH . "classes/Answer.php";

class AnswerDao extends ConnectionFactory
{
    /**
     * @param $row
     * @return Answer|null
     */
    public function fetch($row)
    {
        try {
            $answer = new Answer();
            $answer->id = $row->id;
            $answer->content = $row->content;
            $answer->isCorrect = $row->is_correct;
            $answer->questionId = $row->question_id;
            return $answer;
        } catch (Exception $ex) {
            return null;
        }
    }

    /**
     * @return array
     */
    public function getAll()
    {
        $result = $this->getAllRows(Config::get()->getAnswersTableName());
        $answers = array();
        foreach ($result as $row) {
            $answers[] = $this->fetch($row);
        }
        return $answers;
    }

    /**
     * @param int $id
     * @return array
     */
    public function getAllByQuestionId($id)
    {
        $table = Config::get()->getAnswersTableName();
        $query = "SELECT * FROM $table WHERE question_id=$id";
        global $wpdb;
        $result = $wpdb->get_results($query);

        $answers = array();
        foreach ($result as $row) {
            $answers[] = $this->fetch($row);
        }
        return $answers;
    }

    /**
     * @param Answer $answer
     * @return int
     */
    public function add(Answer $answer)
    {
        global $wpdb;
        $wpdb->insert(
            Config::get()->getAnswersTableName(),
            array(
                "content" => $answer->content,
                "is_correct" => $answer->isCorrect,
                "question_id" => $answer->questionId
            ),
            array("%s", "%d", "%d")
        );
        return $wpdb->insert_id;
    }

    /**
     * @param Answer $answer
     */
    public function edit(Answer $answer)
    {
        global $wpdb;
        $wpdb->update(
            Config::get()->getAnswersTableName(),
            array(
                "content" => $answer->content,
                "is_correct" => $answer->isCorrect,
                "question_id" => $answer->questionId
            ),
            array("id" => $answer->id),
            array("%s", "%d", "%d"),
            array("%d")
        );
    }

    /**
     * @param int $id
     */
    public function remove($id)
    {
        $this->removeRow(
            Config::get()->getAnswersTableName(),
            $id
        );
    }
} 